<template>
  <div class="main" id="main">
    <div>
      <template v-for="litem in list1">
        <section
          v-for="item in litem"
          :key="item.id"
          :style="{ ...item }"
          class="image-container"
        >
          <img :src="item.url" alt="" />
        </section>
      </template>
    </div>
    <div id="right">
      <template v-for="litem in list2">
        <section
          v-for="item in litem"
          :key="item.id"
          :style="{ ...item }"
          class="image-container"
        >
          <img :src="item.url" alt="" />
        </section>
      </template>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from "vue";
import request from "../utils/request";
let list1 = ref([]);
let list2 = ref([]);
let pagination = reactive({
  page: 1,
  limit: 20,
});
let hasGetNewData = ref(false);
const WindowClientHeight = document.documentElement.clientHeight - 160; //允许获取的图片高度在小于一半，大于三分之一
const WindowClientWidth = document.documentElement.clientWidth / 2 - 3;
const getElemHeight = () => {
  return (
    Number(WindowClientHeight / 3 + (WindowClientHeight * Math.random()) / 6) +
    "px"
  );
};
const getMore = (page) => {
  request(
    `https://api.thecatapi.com/v1/images/search`,
    {
      size: "small",
      page: page || pagination.page,
      limit: pagination.limit,
      api_key:
        "live_ovqh93bQshEkfFqkvHcHRLJA5HoeirArF0kIXTrvJn01JrIYxs1js8my7gK8lnYr",
    },
    0
  ).then((res) => {
    let result1 = [];
    let result2 = [];
    for (let i = 0; i < res.data.length; i += 2) {
      result1.push({
        id: res.data[i].id,
        url: res.data[i].url,
        width: WindowClientWidth + "px",
        height: getElemHeight(),
      });
      result2.push({
        id: res.data[i + 1].id,
        url: res.data[i + 1].url,
        width: WindowClientWidth + "px",
        height: getElemHeight(),
      });
    }
    list1.value.push(result1);
    list2.value.push(result2);
    pagination.page++;
  });
};
onMounted(() => {
  getMore(1);
  let main = document.getElementById("main");
  window.onscroll = function (e) {
    let offsetHeight = main.offsetHeight; //元素在屏幕上所用的所有可见区域的高度
    var scrollTop = document.documentElement.scrollTop; //  获取或设置一个元素的内容垂直滚动的像素数
    if (scrollTop + WindowClientHeight * 2 > offsetHeight) {
      if (!hasGetNewData.value) {
        getMore();
      }
    }
  };
});
</script>
<style scoped lang='less'>
.main {
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 60px 0;
  overflow-y: auto;
  div {
    display: flex;
    flex-direction: column;
  }
  .image-container {
    background-clip: border-box;
    display: flex;
    align-items: center;
    background: rgba(245, 243, 237, 1);
    box-shadow: 2px 2px 4px 0px rgba(0, 0, 0, 0.15);
    margin-bottom: 6px;
    border-radius: 8px;
    img {
      width: 100%;
      max-height: fit-content;
    }
  }
}
</style>